﻿CREATE PROCEDURE [dbo].[yaf_topic_delete](
                @TopicID        INT,
                @UpdateLastPost BIT  = 1,
                @EraseTopic     BIT  = 0)
AS
    BEGIN
        SET NOCOUNT  ON
        DECLARE  @ForumID INT
        DECLARE  @pollID INT
        SELECT @ForumID = ForumID
        FROM   yaf_Topic
        WHERE  TopicID = @TopicID
        UPDATE yaf_Topic
        SET    LastMessageID = NULL
        WHERE  TopicID = @TopicID
        UPDATE yaf_Forum
        SET    LastTopicID = NULL,
               LastMessageID = NULL,
               LastUserID = NULL,
               LastUserName = NULL,
               LastPosted = NULL
        WHERE  LastMessageID IN (SELECT MessageID
                          FROM   yaf_Message
                          WHERE  TopicID = @TopicID)
        UPDATE yaf_Active
        SET    TopicID = NULL
        WHERE  TopicID = @TopicID
        --remove polls
        SELECT @pollID = pollID
        FROM   yaf_topic
        WHERE  TopicID = @TopicID
        IF (@pollID IS NOT NULL)
        BEGIN
            DELETE FROM yaf_choice
            WHERE       PollID = @PollID
            UPDATE yaf_topic
            SET    PollID = NULL
            WHERE  TopicID = @TopicID
            DELETE FROM yaf_poll
            WHERE       PollID = @PollID
        END
        --delete messages and topics
        DELETE FROM yaf_nntptopic
        WHERE       TopicID = @TopicID
        DELETE FROM yaf_topic
        WHERE       TopicMovedID = @TopicID
        IF @EraseTopic = 0
        BEGIN
            UPDATE yaf_topic
            SET    Flags = Flags | 8
            WHERE  TopicID = @TopicID
        END
        ELSE
        BEGIN
            DELETE FROM yaf_attachment
            WHERE       MessageID IN (SELECT MessageID
                          FROM   yaf_message
                          WHERE  TopicID = @TopicID)
            DELETE FROM yaf_message
            WHERE       TopicID = @TopicID
            DELETE FROM yaf_topic
            WHERE       TopicID = @TopicID
        END
        --commit
        IF @UpdateLastPost <> 0
        EXEC yaf_forum_updatelastpost
             @ForumID
        IF @ForumID IS NOT NULL
        EXEC yaf_forum_updatestats
             @ForumID
    END


